from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import os
from dotenv import load_dotenv
from django.conf import settings
import requests
import json

from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import AllowAny

load_dotenv()

@authentication_classes([])  # 清空认证类
@permission_classes([AllowAny])  # 允许任何人访问
class DeepSeekSearch(APIView):
    # 初始化对话历史
    conversation_history = []

    def post(self, request):
        try:
            query = request.data.get('query')
            if not query:
                return Response({'error': 'Query is required'}, status=status.HTTP_400_BAD_REQUEST)

            # 将用户输入添加到对话历史
            self.conversation_history.append({"role": "user", "content": query})

            url = "https://api.gpt.ge/v1/chat/completions"
            payload = json.dumps({
                "model": "deepseek-chat",
                "messages": self.conversation_history,  # 传递整个对话历史
                "max_tokens": 1688,
                "temperature": 0.5,
                "stream": False
            })
            headers = {
                'Authorization': f'Bearer {settings.V3API_API_KEY}',
                'Content-Type': 'application/json'
            }

            response = requests.request(
                "POST",
                url,
                headers=headers,
                data=payload,
                timeout=settings.DEEPSEEK_API_TIMEOUT
            )
            response.raise_for_status()

            response_data = response.json()
            assistant_reply = response_data.get('choices', [{}])[0].get('message', {}).get('content', '')

            if not assistant_reply:
                return Response(
                    {'error': 'No valid response from the model'},
                    status=status.HTTP_502_BAD_GATEWAY
                )

            # 将助手的回复添加到对话历史
            self.conversation_history.append({"role": "assistant", "content": assistant_reply})

            return Response({'result': assistant_reply})

        except requests.Timeout:
            return Response(
                {'error': 'Request timed out'},
                status=status.HTTP_504_GATEWAY_TIMEOUT
            )
        except requests.RequestException as e:
            return Response(
                {'error': f'Request failed: {str(e)}'},
                status=status.HTTP_502_BAD_GATEWAY
            )
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )